package com.heima.wemedia.delay;

import com.heima.common.delayTask.RedisDelayedQueueUtil;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.service.WmNewsAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisDelayQueue {


    @Autowired
    private RedisDelayedQueueUtil queueUtil;

    @Autowired
    private WmNewsAuditService wmNewsAuditService;


    @PostConstruct
    public void runTask(){
        log.info("=============runTask 初始化==========");
//        周期性执行任务的线程池
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
//        执行任务，周期性的到延迟队列获取元素,Rate 固定频率 delay 固定延迟
        executorService.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
//                从redis延迟队列获取元素
                    Object obj = queueUtil.getDelayQueue("wm.news.pub");
                    Integer wmNewsId = Integer.valueOf(obj.toString());
                    log.info("=====--------wmNewsId={}",wmNewsId);
                    if(wmNewsId != 0){
//                    调用方法 ，文章发布
                        log.info("发布文章 wmNewsId={}",wmNewsId);
                        WmNews wmNews = new WmNews();
                        wmNews.setId(wmNewsId);
                        wmNewsAuditService.publishWmNews(wmNews,2);
                    }
                }catch (Exception e){
                    log.error("获取延迟队列元素 异常");
                    e.printStackTrace();
                }
            }
        },0,1, TimeUnit.SECONDS);

//        存放一个无用元素，用来激活微服务和redis队列的监听
        queueUtil.addQueue(0,1,TimeUnit.SECONDS,"wm.news.pub");

    }



}
